package com.myjob.utils;



import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class RSAUtils {

	// 加密数据和秘钥的编码方式
	public static final String UTF_8 = "UTF-8";

	public static final String RSA_ALGORITHM_NOPADDING = "RSA";

	/**
	 *  RSA解密方法
	 *  @param privateKeyStr 私钥
	 *  @param data 待解密的数据
	 */
	public static String decryptRSADefault(String privateKeyStr,String data) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NOPADDING);
		byte[] privateKeyArray = privateKeyStr.getBytes();
		byte[] dataArray = data.getBytes();
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyArray));
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

		Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NOPADDING);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return new String(cipher.doFinal(Base64.decodeBase64(dataArray)), UTF_8);
	}

}
